package com.ruoyi.qiuyue.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.qiuyue.common.JWTUtils;
import com.ruoyi.qiuyue.common.UserConstat;
import io.netty.util.CharsetUtil;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对用户进行鉴权
 */
public class AuthFilter extends OncePerRequestFilter  {
    private JWTUtils jwtUtils;

    public AuthFilter(JWTUtils jwtUtils){
        this.jwtUtils = jwtUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 检查是否登录
        boolean isLogin = jwtUtils.checkToken(request);
        if (isLogin) {
            filterChain.doFilter(request, response);
            return;
        }
        // 响应未登录信息
        outNotLogin(response);
    }

    /**
     * 响应未登录信息
     * @param response
     * @throws IOException
     */
    private void outNotLogin(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        ServletOutputStream outputStream = response.getOutputStream();
        // 响应未登录信息
        AjaxResult error = AjaxResult.error(UserConstat.USER_NO_LOGIN_CODE, UserConstat.USER_NO_LOGIN);
        ObjectMapper mapper = new ObjectMapper();
        String errorMsg = mapper.writeValueAsString(error);
        outputStream.write(errorMsg.getBytes(CharsetUtil.UTF_8));
        outputStream.flush();
    }
}